package test

import com.gitee.ixtf.guice.Jguice
import com.gitee.ixtf.vertx.guice.VertxGuice
import com.gitee.ixtf.vertx.verticle.BaseCoroutineVerticle
import io.vertx.core.Vertx
import io.vertx.kotlin.coroutines.coAwait
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.withContext

private var scList = listOf<SendChannel<String>>()

private val vertx: Vertx by Jguice

suspend fun main() {
  Jguice.init(VertxGuice(Vertx.vertx()))

  val channel1 = Channel<String>()
  scList += channel1
  val alg1 = SelectVerticle("channel1", channel1)
  vertx.deployVerticle(alg1).coAwait()

  val channel2 = Channel<String>()
  scList += channel2
  val alg2 = SelectVerticle("channel2", channel2, delaySeconds = 3)
  vertx.deployVerticle(alg2).coAwait()

  (1..10).forEach { v -> select { scList.forEach { sc -> sc.onSend("$v") {} } } }

  println("success")
}

private class SelectVerticle(
    private val name: String,
    private val tasks: ReceiveChannel<String>,
    private val delaySeconds: Int = 1,
) : BaseCoroutineVerticle() {
  override suspend fun start() {
    super.start()
    launch {
      tasks.consumeEach {
        withContext(Dispatchers.Default) {
          log.info("$name handle $it")
          delay(delaySeconds.seconds)
        }
      }
    }
  }
}
